<template>
  <div class="hydrograph">
    <div class="header">
      <BasicForm @register="register" @submit="getStationData" style="width: 100%" />
    </div>
    <!-- 内容区域 -->
    <div class="content">
      <!-- 图表 -->
      <TableChart
        :chartOption="state.chartOption"
        :isShowTable="state.isShowTable"
        :isShowTipIndex="state.isShowTipIndex"
      />
      <!-- 侧边栏内容区域 -->
      <div class="basicInfoTableList" :class="{ isShowTable: !state.isShowTable }">
        <TableList
          :tableDataSource="state.tableDataSource"
          :tableColumns="state.tableColumns"
          rowKey="time"
          @cellClick="cellClick"
        />
        <!-- 显示隐藏侧边栏内容区域 -->
        <div
          class="showTableBtn"
          :class="{ isRotate: !state.isShowTable }"
          @click="state.isShowTable = !state.isShowTable"
        >
          <Icon icon="tabler:caret-left-filled" size="20" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, watch, inject, onMounted } from "vue";
import dayjs from "dayjs";
import TableChart from "@/components/TableChart";
import TableList from "@/components/TableList";
import setChartOption from "./historicalChartOption";
import { Icon } from "@gui-pkg/components";
import { BasicForm, FormSchema, useForm } from "@gui-pkg/antdcomponents";
import { getChartHistory } from "@/api/realTime/realData";

defineOptions({ name: "HistoricalComparison" });

const year = dayjs().format("YYYY");
const defaultTime = [dayjs().subtract(1, "month"), dayjs()];
let yearOptions = [...Array(10)].map((_, i) => ({ value: year - i }));
const schemas: FormSchema[] = [
  {
    field: "time",
    component: "RangePicker",
    defaultValue: defaultTime,
    label: "起止时间",
    colProps: { span: 7 },
  },
  {
    field: "years",
    component: "Select",
    label: "年份选择",
    colProps: { span: 8 },
    defaultValue: [Number(year), year - 1, year - 2],
    componentProps: {
      mode: "multiple",
      maxTagCount: 3,
      maxTagTextLength: 4,
      options: yearOptions,
    },
  },
  {
    field: "type",
    component: "RadioGroup",
    label: "",
    colProps: { offset: 1, span: 4 },
    defaultValue: "inz",
    componentProps: {
      options: [
        { label: "闸内水位", value: "inz" },
        { label: "闸外水位", value: "otz" },
      ],
    },
  },
];

const [register, { getFieldsValue }] = useForm({
  labelWidth: 80,
  schemas,
  actionColOptions: { span: 3 },
});

const cellClick = ({ params, index }) => {
  state.isShowTipIndex = state.tableDataSource.length - index - 1;
};

const state = reactive({
  isShowTable: true,
  chartOption: null,
  isShowTipIndex: -1,
  tableDataSource: [],
  tableColumns: [{ dataIndex: "time", title: "标志时间", align: "center" }],
});

const props = defineProps({
  data: { type: Object },
});

// 后台获取站点数据
const getStationData = async (data = null) => {
  if (props?.data?.stcd) {
    const params = {
      stcd: props?.data?.stcd,
      startTime:
        data?.time && data.time.length ? dayjs(data.time[0]).format("MM-DD") : "",
      endTime: data?.time && data.time.length ? dayjs(data.time[1]).format("MM-DD") : "",
      years: data?.years.join(","),
      type: "",
    };
    const stationData = await getChartHistory("gate", params);
    let dataSourceData = [];
    let tableColumns = [{ dataIndex: "time", title: "标志时间", align: "center" }];
    for (let year in stationData) {
      tableColumns.push({ dataIndex: year, title: year, align: "center" });
      for (let i = 0; i < stationData[year].length; i++) {
        if (!dataSourceData[i]) {
          dataSourceData[i] = {};
        }
        dataSourceData[i][year] = stationData[year][i][data.type];
        dataSourceData[i].time = dayjs(stationData[year][i].tmMin).format("MM-DD");
      }
    }
    // 自定义排序函数
    function sortByDataIndexDescending(a, b) {
      // 将数字字符串转换为数字进行比较
      let numA = parseInt(a.dataIndex, 10);
      let numB = parseInt(b.dataIndex, 10);
      // 比较数字，实现降序排序
      if (numA > numB) { return -1; }
      if (numA < numB) { return 1; }
      return 0;
    }
    // 使用sort方法进行排序
    let sortedArray = tableColumns.sort(sortByDataIndexDescending);
    state.tableColumns = sortedArray;
    state.tableDataSource = dataSourceData.reverse();
    state.chartOption = setChartOption(stationData, data.years, data.type, props.data);
  }
};

// 初始化数据
const initData = async () => {
  const values = await getFieldsValue();
  if (!values.time) {
    const year = dayjs().format("YYYY");
    values.time = [defaultTime[0].format("MM-DD"), defaultTime[1].format("MM-DD")];
    values.years = [Number(year), year - 1, year - 2];
    values.type = "inz";
  }
  await getStationData(values);
};

// 监听是否点击了全屏，重新渲染下
const modalHeightChange = inject("ModalHeightChange");
watch(
  () => modalHeightChange.value,
  () => {
    initData();
  }
);

onMounted(() => {
  initData();
});
</script>

<style lang="less" rel="stylesheet/less" scoped>
.hydrograph {
  width: 100%;
  height: 100%;
  .header {
    width: 100%;
    height: 32px;
    display: flex;
    align-items: center;
    margin-bottom: 18px;
    ::v-deep(.ant-form-item) {
      margin-bottom: 0 !important;
    }
    .step {
      margin-left: 10px;
      margin-right: 30px;
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 50px);
    display: flex;
    align-items: center;
    position: relative;
    .basicInfoTableList {
      width: 390px;
      height: 100%;
      display: flex;
      flex-direction: column;
      position: absolute;
      right: 0;
      transition: all 0.5s;
    }
    .showTableBtn {
      position: absolute;
      top: 40%;
      left: -22px;
      z-index: 200;
      width: 24px;
      height: 120px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      border-radius: 6px;
      transition: all 0.5s;
      transform: translate(0px, -50%) rotate(180deg);
      background: url(@/assets/svg/sideBar.svg) no-repeat;
      span {
        margin-top: -20px;
        font-size: 18px;
        color: #c4c4c4;
        transform: rotate(0deg);
        transition: all 0.3s;
      }
      &:hover {
        span {
          color: #5780fa;
        }
      }
    }
    .isRotate {
      span {
        transform: rotate(180deg);
      }
    }
  }
  .isShowTable {
    right: -390px !important;
  }
}
</style>
